package com.yantong.quartz.job;

import com.yantong.pojo.Centre;
import com.yantong.service.CentreService;
import com.yantong.utils.DateUtils;
import com.yantong.pojo.WorkConfig;
import com.yantong.mapper.WorkConfigMapper;
import com.yantong.mapper.WorkOrderMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 售后工单定时任务
 * @author kanghaixin
 * @date 2018/9/7.10:35
 */
@Service
public class WorkTimer {
    private static final Logger logger = LoggerFactory.getLogger(WorkTimer.class);
    @Autowired
    private WorkOrderMapper workOrderMapper;
    @Autowired
    private WorkConfigMapper workConfigMapper;
    @Autowired
    private CentreService centreService;

        private boolean taskOn = true;

    /**
     *
     * 检测工单是否处理超时，每日一点重检查一次
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void checkWorkTimeOut () {
        if (!taskOn) {
            logger.info("system task set off!checkWorkTimeOut!");
            return;
        }
        List<Centre> centres = centreService.listAllCentres();
        logger.info("checkWorkTimeOut start, centre size :{}", centres.size());
        if (CollectionUtils.isEmpty(centres)) {
            logger.info("not found centre!");
            return;
        }

        for (Centre centre: centres) {
            if (centre == null || centre.getCentreId() == null) {
                continue;
            }
            WorkConfig workConfig = workConfigMapper.getByCentreId(centre.getCentreId());
            int hours = 0;
            if (workConfig == null || workConfig.getWorkTime() == null) {
                hours = 48;
            }else {
                hours = workConfig.getWorkTime();
            }
            int result = workOrderMapper.checkWorkTimeOut(DateUtils.getAddHourDate(new Date(), - hours), centre.getCentreId());
            logger.info("centre:{} check work order time out over,check size:{}", centre.getName(), result);
        }
        logger.info("checkWorkTimeOut all end");
    }
}
